package com.wx.resume_excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.wx.common.api.CommonPage;
import com.wx.common.api.CommonResult;
import com.wx.common.api.ResultCode;
import com.wx.resume_excel.listener.CustomCellWriteHandler;
import com.wx.resume_excel.listener.HyperLinkHandler;
import com.wx.resume_excel.model.JobSeeker;
import com.wx.resume_excel.model.ResumeTemplate;
import com.wx.resume_excel.model.SelectModel;
import com.wx.resume_excel.service.ExcelResumeService;
import com.wx.resume_excel.utils.ExcelUtil;
import com.wx.resume_excel.vo.JobSeekerVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * excel读取/存储的control层
 *
 * @Auther 田艺鹏
 * @DateTime 2020-08-03 10:47
 */

@RestController
@RequestMapping("/excelResume")
public class ExcelResumeController {
    @Autowired
    private ExcelResumeService resumeService;

    @ApiOperation(value = "简历读取并存储相关数据", notes = "io读取相关数据并存储")
    @PostMapping("/upload")
    public CommonResult fileUpload2 ( @RequestParam("file") MultipartFile file ) throws IOException {
        String fileName = file.getOriginalFilename ( );
        File fileDir = new File ( "F:/tns-server/tns-resume-excel/src/main/resources/static" );
        if (!fileDir.exists ( )) {
            fileDir.mkdir ( );
        }
        String path = fileDir.getAbsolutePath ( );
        file.transferTo ( new File ( fileDir.getAbsolutePath ( ),fileName ) );

        path = path + "\\" + fileName;
//        return null;
        return readExcelAndSave ( path );
    }

    /**
     * 写出数据库对应数据的接口
     */
    @PostMapping("/writeDate")
    @ApiOperation(value = "读取数据库数据写入数据")
    public String writeExcel ( @RequestParam("numbers") String numbers ) {
        numbers = numbers.substring ( 0,numbers.length ( ) - 1 );

        String[] resumeNos = numbers.split ( "," );

        List<JobSeeker> jobSeekerList = new ArrayList<> ( );
        List<ResumeTemplate> templateFillData = new ArrayList<> ( );


        for (int i = 0; i < resumeNos.length; i++) {
            ResumeTemplate resumeTemplate = resumeService.selectByResumeNo ( resumeNos[i] );
            JobSeeker jobSeeker = resumeService.selectSeekerByResumeNo ( resumeNos[i] );
            jobSeekerList.add ( jobSeeker );
            templateFillData.add ( resumeTemplate );
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ( "yyyyMMdd" );
        String fileName = simpleDateFormat.format ( new Date ( ) );
        String filePath = "F:/tns-server/tns-resume-excel/src/main/resources/static/" + fileName + ".xlsx";

        ExcelWriter workbook = EasyExcel.write ( filePath ).build ( );
        WriteSheet writeSheet;

        if (jobSeekerList.size ( ) <= 0 || templateFillData.size ( ) <= 0) {
            return "失败";
        }
        for (int i = 0; i <= jobSeekerList.size ( ); i++) {
            if (i == 0) {
                writeSheet = EasyExcel.writerSheet ( i,"UserList" )
                        .head ( JobSeeker.class )
                        .registerWriteHandler ( new HyperLinkHandler ( ) )
                        .build ( );
                workbook.write ( jobSeekerList,writeSheet );
            } else if (i > 0 && i <= jobSeekerList.size ( )) {
                writeSheet = EasyExcel.writerSheet ( i,i + "." + jobSeekerList.get ( i - 1 ).getName ( ) )
                        .registerWriteHandler ( new CustomCellWriteHandler ( ) ) //监听器 （可以通过行/列的具体情况进行格式实现）
                        .build ( );
                workbook.write ( ExcelUtil.createTable ( templateFillData.get ( i - 1 ) ),writeSheet );
            }
        }
        // finish 关闭流
        workbook.finish ( );
        return fileName;
    }


//    @PostMapping("/selectJobSeeker")
//    @ApiOperation(value = "获取用户信息")
//    public CommonResult selectJobSeeker(@RequestBody SelectModel selectModel){
//        List<JobSeeker> list = resumeService.selectBySelectModel(selectModel);
//        if(list.size() <= 0){
//            return CommonResult.failed();
//        }
//        return CommonResult.success(CommonPage.restPage(list));
//
//    }

    @PostMapping("/selectJobSeeker")
    @ApiOperation(value = "获取用户信息")
    public CommonResult selectJobSeeker () {
        List<JobSeeker> jobSeekers = resumeService.selectJobSeeker ();
        if (jobSeekers.size ( ) <= 0) {
            return CommonResult.failed ("查询失败");
        }
        return CommonResult.success ( jobSeekers,"查询成功" );

    }


    @ApiOperation(value = "求职者分页查询", notes = "求职者分页查询")
    @RequestMapping(value = "/findByJobSeekerPage", method = RequestMethod.POST)
    public CommonResult findByJobSeekerPage (JobSeekerVo jobSeekerVo ) {
        PageInfo byJobSeekerPage = resumeService.findByJobSeekerPage ( jobSeekerVo );
        try {
            if (byJobSeekerPage == null) {
                return CommonResult.failed ( "查询数据失败!" );
            } else {
                return CommonResult.success ( byJobSeekerPage,"查询数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @PostMapping("/selectByResumeNo")
    @ApiOperation(value = "通过简历编码获取详细简历", notes = "获取详细简历")
    public CommonResult selectByResumeNo ( @RequestBody String resumeNo ) {

        /**
         * 如果是直接传string 代码如下
         * @RequestParam("resumeNo") String resumeNo
         * ResumeTemplate resumeTemplate = resumeService.selectByResumeNo(resumeNo)
         */
        String[] split = resumeNo.split ( ":" );
        String str = split[1].substring ( 1,split[1].length ( ) - 2 ).trim ( );

        ResumeTemplate resumeTemplate = resumeService.selectByResumeNo ( str.replaceAll ( "\\\"","" ) );
        if (resumeTemplate == null) {
            return CommonResult.failed ( );
        }
        return CommonResult.success ( resumeTemplate );
    }

    @PostMapping("/deleteStaticFile")
    @ApiOperation(value = "删除缓存文件")
    public CommonResult deleteStaticFile () {
        File file = new File ( "F:/tns-server/tns-resume-excel/src/main/resources/static/" );
        if (file.isDirectory ( )) {
            File[] files = file.listFiles ( );
            if (files == null) {
                return CommonResult.failed ( "缓存区域无文件！" );
            } else {
                for (int i = 0; i < files.length; i++) {
                    files[i].delete ( );
                }
            }
        }
        return CommonResult.success ( "文件缓存已删除！" );
    }

    private String getResumeNo ( ResumeTemplate resumeTemplate ) {
        String callPhone = resumeTemplate.getCallPhone ( );
        JobSeeker jobSeeker = resumeService.selectByCallPhone ( callPhone );
        if (jobSeeker.getResumeNo ( ) == null) {
            String resumeNo = ExcelUtil.createResumeNo ( jobSeeker.getCallPhone ( ) );
            while (resumeService.selectByResumeNo ( resumeNo ) != null) {
                System.out.println ( "while" );
                resumeNo = ExcelUtil.createRoundResumeNo ( );
            }
            jobSeeker.setResumeNo ( resumeNo );
            resumeService.updateResumeNo ( jobSeeker );
            resumeTemplate.setResumeNo ( jobSeeker.getResumeNo ( ) );
        } else {
            resumeTemplate.setResumeNo ( jobSeeker.getResumeNo ( ) );
        }
        return resumeTemplate.getResumeNo ( );
    }

    /**
     * 读取和存储数据的方法
     */
    private CommonResult readExcelAndSave ( String filePath ) {
        //存储workEx
        String[] workExperience = new String[10];
        int[] workCount = {0};

        //存储projectEx
        String[] projectExperience = new String[10];
        int[] projectCount = {0};

        //存储 resume_template 数据
        String[] templateDate = new String[75];

        File file = new File ( filePath );
        if (!file.exists ( )) {
            return CommonResult.failed ( "文件不存在！" );
        }

        ExcelReader workBook = EasyExcel.read ( filePath,new AnalysisEventListener ( ) {
            @Override
            public void invoke ( Object o,AnalysisContext analysisContext ) {
                //读取sheet1的方法
                if (analysisContext.getCurrentSheet ( ).getSheetNo ( ) == 1 && analysisContext.getCurrentRowNum ( ) > 0) {
                    JobSeeker jobSeeker = ExcelUtil.readJobSeeker ( o );
                    /**
                     * 判断数据库中是否已经有此数据 结果为true时进行存储
                     */
                    JobSeeker jobSeeker1 = resumeService.selectByCallPhone ( jobSeeker.getCallPhone ( ) );
                    if (jobSeeker1 == null) {
                        resumeService.addJobSeeker ( jobSeeker );
                    }
                }

                if (analysisContext.getCurrentSheet ( ).getSheetNo ( ) >= 2 && analysisContext.getCurrentRowNum ( ) > 0) {
                    String resumeTemplateStr = o.toString ( );

                    String[] split = resumeTemplateStr.split ( "=" );

                    /**
                     * 判断是否为自己创建的模板文件
                     */
                    if (!"null, 1".equals ( split[1] )) {
                        String attribute = split[2].replace ( "}","" );

                        templateDate[analysisContext.getCurrentRowNum ( ) - 1] = attribute;

                        if (analysisContext.getCurrentRowNum ( ) == 73) {
                            for (int i = 0; i < templateDate.length; i++) {
                                if ("null".equals ( templateDate[i] ) || templateDate[i] == null) {
                                    templateDate[i] = "";
                                }
                            }

                            ResumeTemplate resumeTemplate = new ResumeTemplate (
                                    templateDate[0],templateDate[1],templateDate[2],templateDate[3],templateDate[5],
                                    templateDate[7],templateDate[8],templateDate[9],templateDate[10],templateDate[11],templateDate[12],templateDate[13],templateDate[14],
                                    templateDate[15],templateDate[16],templateDate[17],templateDate[18],templateDate[19],templateDate[20],templateDate[21],templateDate[22],
                                    templateDate[24],templateDate[25],templateDate[26],templateDate[27],templateDate[28],templateDate[30],templateDate[31],templateDate[32],
                                    templateDate[33],templateDate[34],templateDate[35],templateDate[36],templateDate[37],templateDate[39],templateDate[40],templateDate[41],
                                    templateDate[42],templateDate[43],templateDate[44],templateDate[45],templateDate[46],templateDate[47],templateDate[48],templateDate[50],
                                    templateDate[51],templateDate[52],templateDate[53],templateDate[54],templateDate[55],templateDate[56],templateDate[57],templateDate[58],
                                    templateDate[59],templateDate[61],templateDate[63],templateDate[64],templateDate[66],templateDate[67],templateDate[68],templateDate[70],
                                    templateDate[72] );

                            String resumeNo = getResumeNo ( resumeTemplate );
                            resumeTemplate.setResumeNo ( resumeNo );

                            if (resumeService.selectByResumeCallPhone ( resumeTemplate.getCallPhone ( ) ) == null) {
                                resumeService.addTemplateResume ( resumeTemplate );
                            }

                            for (int i = 0; i < templateDate.length; i++) {
                                templateDate[i] = "";
                            }
                        }

                    } else {
                        String columnName = split[2].replace ( "}","" );

                        if (analysisContext.getCurrentRowNum ( ) == 41 && split.length == 3) {
                            if ((columnName == "工作经验" || "工作经验".equals ( columnName )) && workCount[0] == 0) {
                                workCount[0] = 1;
                                for (int i = 41; i < 50; i++) {
                                    templateDate[i] = "";
                                }
                            }
                        } else if (analysisContext.getCurrentRowNum ( ) == 41 + workCount[0] + 1 && split.length == 3) {
                            if ((columnName == "项目经验" || "项目经验".equals ( columnName )) && projectCount[0] == 0) {
                                projectCount[0] = 1;
                                for (int i = 52; i < 61; i++) {
                                    templateDate[i] = "";
                                }
                            }
                        }

                        if (split.length == 4) {
                            String attribute = split[3].replace ( "}","" );
                            columnName = columnName.split ( "," )[0];
                            if (columnName == "工作经验" || "工作经验".equals ( columnName )) {
                                workExperience[workCount[0]] = attribute;
                                workCount[0]++;
                            }

                            if ((columnName == "项目经验" || "项目经验".equals ( columnName )) && (attribute != "null" || !"null".equals ( attribute ))) {
                                projectExperience[projectCount[0]] = attribute;
                                projectCount[0]++;
                            }

                            if (analysisContext.getCurrentRowNum ( ) < 40) {
                                templateDate[analysisContext.getCurrentRowNum ( )] = attribute;
                            } else if (analysisContext.getCurrentRowNum ( ) > 41 + projectCount[0] + projectCount[0] + 1) {
                                if (columnName == "教育经历" || "教育经历".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[63] = attribute;
                                    } else {
                                        templateDate[63] = "";
                                    }
                                } else if (columnName == "校内荣誉" || "校内荣誉".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[65] = attribute;
                                    } else {
                                        templateDate[65] = "";
                                    }
                                } else if (columnName == "校内职务" || "校内职务".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[66] = attribute;
                                    } else {
                                        templateDate[66] = "";
                                    }
                                } else if (columnName == "技能/语言" || "技能/语言".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[68] = attribute;
                                    } else {
                                        templateDate[68] = "";
                                    }
                                } else if (columnName == "证书" || "证书".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[69] = attribute;
                                    } else {
                                        templateDate[69] = "";
                                    }
                                } else if (columnName == "培训经历" || "培训经历".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[70] = attribute;
                                    } else {
                                        templateDate[70] = "";
                                    }
                                } else if (columnName == "其他" || "其他".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[72] = attribute;
                                    } else {
                                        templateDate[72] = "";
                                    }
                                } else if (columnName == "求职信" || "求职信".equals ( columnName )) {
                                    if (attribute != null || !"".equals ( attribute )) {
                                        templateDate[74] = attribute;
                                    } else {
                                        templateDate[74] = "";
                                    }
                                }
                            }
                        }

                        /**
                         * 扫描到最后一行后执行具体操作
                         */
                        if (analysisContext.getCurrentRowNum ( ) == 55 + workCount[0] + projectCount[0] - 1 || analysisContext.getCurrentRowNum ( ) == 74) {
                            //输出每一个sheet中最大的扫描数
                            if (workExperience[0] != null && !"".equals ( workExperience[0] )) {
                                for (int i = 0; i < workCount[0]; i++)
                                    templateDate[41 + i] = workExperience[i];

                            }

                            if (projectExperience[0] != null && !"".equals ( projectExperience[0] )) {
                                for (int i = 0; i < projectCount[0]; i++)
                                    templateDate[52 + i] = projectExperience[i];
                            }

                            for (int i = 0; i < templateDate.length; i++) {
                                if (templateDate[i] == null) {
                                    templateDate[i] = "";
                                }

                            }

                            ResumeTemplate resumeTemplate = new ResumeTemplate (
                                    templateDate[2],templateDate[3],templateDate[4],templateDate[5],templateDate[7],
                                    templateDate[9],templateDate[10],templateDate[11],templateDate[12],templateDate[13],templateDate[14],templateDate[15],templateDate[16],
                                    templateDate[17],templateDate[18],templateDate[19],templateDate[20],templateDate[21],templateDate[22],templateDate[23],templateDate[24],
                                    templateDate[26],templateDate[27],templateDate[28],templateDate[29],templateDate[30],templateDate[32],templateDate[33],templateDate[34],
                                    templateDate[35],templateDate[36],templateDate[37],templateDate[38],templateDate[39],templateDate[41],templateDate[42],templateDate[43],
                                    templateDate[44],templateDate[45],templateDate[46],templateDate[47],templateDate[48],templateDate[49],templateDate[50],templateDate[52],
                                    templateDate[53],templateDate[54],templateDate[55],templateDate[56],templateDate[57],templateDate[58],templateDate[59],templateDate[60],
                                    templateDate[61],templateDate[63],templateDate[65],templateDate[66],templateDate[68],templateDate[69],templateDate[70],templateDate[72],
                                    templateDate[74] );

                            String resumeNo = getResumeNo ( resumeTemplate );
                            resumeTemplate.setResumeNo ( resumeNo );

                            if (resumeService.selectByResumeCallPhone ( resumeTemplate.getCallPhone ( ) ) == null) {
                                resumeService.addTemplateResume ( resumeTemplate );
                            }

                            /**
                             * 初始化操作
                             */
                            workCount[0] = projectCount[0] = 0;
                            for (int i = 0; i < workExperience.length; i++) {
                                workExperience[i] = "";
                            }
                            for (int i = 0; i < projectExperience.length; i++) {
                                projectExperience[i] = "";
                            }
                            for (int i = 0; i < templateDate.length; i++) {
                                templateDate[i] = "";
                            }
                        }
                    }
                }
            }

            @Override
            public void doAfterAllAnalysed ( AnalysisContext analysisContext ) {
            }
        } ).build ( );

        workBook.readAll ( );

        return CommonResult.success ( "文件已成功创建" );
    }
}
